package net.borlis.errors.providers.implementation.filebase;

import net.borlis.errors.exceptions.IExceptionKeyMaster;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.net.URL;
import java.util.HashSet;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author alex@borlis.net
 */
@ApplicationScoped
public class LocalMessageProvider implements ILocalMessageProvider {

    private static final String FILENAME_SEPARATOR = "_";
    private static final String LOCALE_SEPARATOR = "-";
    private static final String FILE_NAME = "errorsMessages";

    @Inject
    private Logger logger;

    private Set<Locale> supportedLocales;

    @PostConstruct
    public void init() {
        logger.info("init bundles based translation");
        supportedLocales = new HashSet<>();
        // -=-=-=-
        ResourceBundle.clearCache();
        for (Locale locale : Locale.getAvailableLocales()) {
            logger.log(Level.INFO, "checking locale : " + locale);
//            try {
//                ResourceBundle.getBundle(LocaleFileTranslatedExceptionProcessor.FILE_NAME, locale);
//                logger.info("found file for the locale : " + locale);
//                supportedLocales.add(locale);
//            } catch (MissingResourceException mre){
//                // do nothing <= expected
//            }
            // todo :: find more effective way !!!
            URL propertiesFile = ClassLoader.getSystemResource(FILE_NAME + FILENAME_SEPARATOR + locale + ".properties");
            if(propertiesFile != null) {
                logger.info("found file for the locale : " + locale);
                supportedLocales.add(locale);
            }
        }
        // the last check
        if (supportedLocales.isEmpty()) {
            throw new IllegalStateException("no locales for translation");
        }
    }

    public ResourceBundle getErrorsMessagesBundle(Locale locale) {
        return ResourceBundle.getBundle(FILE_NAME, locale);
    }

    public String getErrorMessage(String strLocale, IExceptionKeyMaster keyMaster) {
        String[] paramsLocales = strLocale.split(LOCALE_SEPARATOR);
        if (paramsLocales.length != 2) {
            throw new IllegalArgumentException("The provided locale " + strLocale + " cannot be parsed");
        }
        Locale locale = prepareLocale(paramsLocales[0], paramsLocales[1]);
        return String.format(getErrorsMessagesBundle(locale).getString(keyMaster.getKey()));
    }

    private Locale prepareLocale(String lang, String country) {
        return new Locale(lang, country);
    }

    @Override
    public Set<Locale> getSupportedLocales() {
        return supportedLocales;
    }

}
